package com.wanban.downloader.utils

import android.text.TextUtils
import com.blankj.utilcode.util.FileUtils
import com.google.gson.Gson
import com.tencent.mmkv.MMKV
import com.wanban.downloader.db.DownloadEntity
import com.wanban.downloader.model.M3U8
import com.wanban.downloader.model.M3U8Seg
import java.io.File

object CacheM3U8Utils {

    private const val TS_LIST_END_FILE_NAME = "TsListEnd"
    private const val TS_LIST_END_FILE_NAME_EXTENSION = ".txt"

    /**
     * 从缓存中回复M3U8
     */
    @Synchronized
    fun getM3U8FromCache(fileName: String): M3U8?{
        try {
////            Log.d("NewTD", "准备从缓存恢复M3U8对象...")
//            // 1.从本地缓存恢复M3U8
//            // /Data/Android/xxx/files/Wanban/${fileName}/Cache/cacheM3U8.txt，包含出了tsList的所有内容
//            val m3u8LocalFile =  FileDownloadPathUtils.getLocalCacheM3U8FilePath(fileName)
////            Log.d("NewTD", "m3u8LocalFile: $m3u8LocalFile")
//            if (!FileUtils.isFileExists(m3u8LocalFile)) return null
//            val m3u8File = File(m3u8LocalFile!!)
//            val m3u8Content = m3u8File.readText()
//            if (TextUtils.isEmpty(m3u8LocalFile)) return null
//            val gson = Gson()
//            val m3u8 = gson.fromJson(m3u8Content, M3U8::class.java)?:return null
////            Log.d("NewTD", "m3u8从缓存恢复成功...")
//            // 2.从本地文件恢复TsList
//            // xxx/fileName/LocalTsList/
//            val localTsListFilePath = FileDownloadPathUtils.getLocalTsListFileDirPath(fileName)?:return null
////            Log.d("NewTD", "localTsListFilePath: $localTsListFilePath...")
//            val localM3U8File = File(localTsListFilePath)
//            // 校验目录文件
//            if (!localM3U8File.exists() || !localM3U8File.isDirectory) return null
//            val tsListFileList = localM3U8File.listFiles()?:return null
//            val fileSize = tsListFileList.size
////            Log.d("NewTD", "tsListCount: $fileSize...")
//            if (fileSize <= 1) return null
//            val endFile = tsListFileList.firstOrNull { it.nameWithoutExtension == TS_LIST_END_FILE_NAME }
//            if (!FileUtils.isFileExists(endFile)) return null
////            Log.d("NewTD", "存在endFile，说明ts缓存是完整的...")
//            // 创建ts集合
//            val tsList = ArrayList<M3U8Seg>()
//            // 按照文件名字，进行升序排序  1.txt, 2.txt, 3.txt
//            tsListFileList.sortBy {
//                val name = it.nameWithoutExtension
//                if (name == TS_LIST_END_FILE_NAME) {
//                     99999
//                } else {
//                    name.toIntOrNull()?:0
//                }
//            }
//            // 解析每个文件的内容，并数据化
//            for (tsListFile in tsListFileList) {
//                if (tsListFile.nameWithoutExtension == TS_LIST_END_FILE_NAME) continue
//                val tsContent = tsListFile.readText()
//                val ts = gson.fromJson(tsContent, M3U8Seg::class.java)
//                tsList.add(ts)
//            }
////            Log.d("NewTD", "TsList从缓存恢复成功...")
//            if (tsList.isEmpty()) return null
//            m3u8.tsList = tsList

            val mmkv = MMKV.defaultMMKV()
            val m3u8Content = mmkv.decodeString(fileName)
            if (TextUtils.isEmpty(m3u8Content)) return null
            val gson = Gson()
            return gson.fromJson(m3u8Content, M3U8::class.java)


//            val m3u8Content = SPUtils.getInstance().getString(fileName)
//            if (TextUtils.isEmpty(m3u8Content)) return null
//            val gson = Gson()
//            val m3u8 = gson.fromJson(m3u8Content, M3U8::class.java)
//            val endTime = System.currentTimeMillis() - startTime
//            Log.e("NewTD", "getM3U8FromCache -> 耗时：$endTime ms" )
//            return m3u8
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }


    /**
     * 将M3U8内容缓存到本地
     */
    @Synchronized
    fun cacheM3U8(task: DownloadEntity): Boolean {
//        if (task.m3u8 == null) return false
//        // 1.写入m3u8
//        // /Data/Android/xxx/files/Wanban/${fileName}/Cache/cacheM3U8.txt，包含出了tsList的所有内容
//        val m3u8LocalFilePath =  FileDownloadPathUtils.getLocalCacheM3U8FilePath(task.getFileName())
//        if (!FileUtils.createOrExistsFile(m3u8LocalFilePath)) return false
////        Log.d("NewTD", "m3u8LocalFilePath: $m3u8LocalFilePath")
//        val m3u8LocalFile = File(m3u8LocalFilePath!!)
//        val gson = Gson()
//        val m3u8Content = gson.toJson(task.m3u8)
//        if (TextUtils.isEmpty(m3u8Content)) return false
//        m3u8LocalFile.writeText(m3u8Content)
//
////        Log.d("NewTD", "m3u8 缓存完成...")
//
//        // 2.写入tsList
//        val tsList = task.m3u8?.tsList?:return false
//        // xxx/fileName/LocalTsList/
//        val localTsListFilePath = FileDownloadPathUtils.getLocalTsListFileDirPath(task.getFileName())
////        Log.d("NewTD", "localTsListFilePath: $localTsListFilePath")
//        if (!FileUtils.createOrExistsDir(localTsListFilePath)) return false
//
//        // 是否所有文件写入成功
//        var isAllWriteSuccess = true
//        for(ts in tsList){
//            // xxx/fileName/LocalTsList/1.txt
//            val tsFile = File(localTsListFilePath, "${ts.index}.txt")
////            Log.d("NewTD", "tsFile: ${tsFile.absolutePath}")
//            if (tsFile.createNewFile()) {
//                val content = gson.toJson(ts)
//                tsFile.writeText(content)
//            } else {
//                isAllWriteSuccess = false
//                break
//            }
//        }
////        Log.d("NewTD", "tsList 缓存完成...")
//        if (!isAllWriteSuccess)  return false
//        // 写入结束标签  // xxx/fileName/LocalTsList/TsListEnd.txt
//        val endFileName = String.format("%s%s", TS_LIST_END_FILE_NAME, TS_LIST_END_FILE_NAME_EXTENSION)
//        val tsListEndFile = File(localTsListFilePath, endFileName)
//        val endTime = System.currentTimeMillis() - startTime
//        Log.e("NewTD", "cacheM3U8 -> 耗时：$endTime ms" )
////        Log.d("NewTD", "TsListEnd 缓存完成..." + tsListEndFile.absolutePath)
//        return tsListEndFile.createNewFile()


        val gson = Gson()
        val m3u8Content = gson.toJson(task.m3u8)

        val mmkv = MMKV.defaultMMKV()
        mmkv.encode(task.getFileName(), m3u8Content)

        return true
    }

    @Synchronized
    fun reCacheM3U8(fileName: String, ts: M3U8Seg){
//        Log.d("NewTD", "准备重新缓存文件...${ts.index}.txt")
        val localTsListFilePath = FileDownloadPathUtils.getLocalTsListFileDirPath(fileName)
//        Log.d("NewTD", "localTsListFilePath...$localTsListFilePath")
        if (FileUtils.isFileExists(localTsListFilePath)) {
            val cacheTsFile = File(localTsListFilePath, "${ts.index}$TS_LIST_END_FILE_NAME_EXTENSION")
//            Log.d("NewTD", "cacheTsFile...${cacheTsFile.absolutePath}")
            if (FileUtils.createOrExistsFile(cacheTsFile)) {
                val tsContent = Gson().toJson(ts)
                cacheTsFile.writeText(tsContent)
//                Log.d("NewTD", "${ts.index}.txt 重新缓存成功...")
            }
        }
    }

    @Synchronized
    fun reCacheM3U8(task: DownloadEntity){
        val gson = Gson()
        val m3u8Content = gson.toJson(task.m3u8)
        val mmkv = MMKV.defaultMMKV()
        mmkv.encode(task.getFileName(), m3u8Content)
    }

    fun clearCacheM3U8(fileName: String){
        MMKV.defaultMMKV().removeValueForKey(fileName)
    }
}